<template lang="pug">
  .ApplyInvoice
    Modal(
      v-model="isShowBalanceProcessModal"
      title="差额处理"
      class-name="vertical-center-modal"
      width="800"
      :mask-closable="false"
    )
      .search-form
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-if="item.isShow")
            template(v-if="item.type === 'text'")
              .line-h-30 {{formData[item.model]}}
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" label-in-value @on-change="handleTypeChange")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'input'")
              //- 正负数均可
              Input(v-if="item.model === 'total'" v-model="formData[item.model]" :placeholder="item.placeholder")
              //- 负数
              Input(v-if="item.model === 'totalMin'" v-model="formData.total" :placeholder="item.placeholder")
              //- 正数
              Input(v-if="item.model === 'totalMax'" v-model="formData.total" :placeholder="item.placeholder")
            template(v-if="item.type === 'textarea'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" type="textarea")
            template(v-if="item.type === 'button'")
              Button.ml-20.pull-right(type="info" @click="handleAddBalance") 添加

      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable" max-height="280")
        .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
          .table-title-lefttxt.pull-left
            |当期差额总计
            span.text-info.pl-5.pr-5.font-weight {{currentRow.balanceTotal}}
            |元
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-10(type="text" size="small" @click="handleDel(index)") 删除

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmit") 确定
</template>

<script>
// import { InvoiceApi } from '@/api/Invoice.api.js'
import { BalanceApi } from '@/api/Balance.api.js'
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { BalanceProcessModalThead } from '../tableHead.js'
export default {
  name: '',

  data () {
    const validateTotal = (rule, value, callback) => {
      if (!this.formData.total || this.formData.total == 0) {
        callback(new Error('请输入非0的数字'))
      } else {
        callback()
      }
    }
    const validateTotalMax = (rule, value, callback) => {
      if (!this.formData.total || this.formData.total <= 0) {
        callback(new Error('请输入大于0的数字'))
      } else {
        callback()
      }
    }
    const validateTotalMin = (rule, value, callback) => {
      if (!this.formData.total || this.formData.total >= 0) {
        callback(new Error('请输入小于0的数字'))
      } else {
        callback()
      }
    }

    return {
      isShowBalanceProcessModal: false,
      thead: _cloneDeep(BalanceProcessModalThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      formData: {
        handleType: '',
        handleTypeName: '',
        total: '',
        remark: ''
      },
      formItem: [
        { type: 'select', label: '处理方式', placeholder: '请选择处理方式', prop: 'handleType', model: 'handleType', style: 'ivu-col-span-12', options: 'balancehandle', isShow: true },
        { type: 'input', label: '处理差额', placeholder: '请输入处理差额', prop: 'total', model: 'total', style: 'ivu-col-span-12', isShow: true },
        { type: 'input', label: '处理差额', placeholder: '请输入处理差额（只能填写负数）', prop: 'totalMin', model: 'totalMin', style: 'ivu-col-span-12', isShow: false },
        { type: 'input', label: '处理差额', placeholder: '请输入处理差额（只能填写正数）', prop: 'totalMax', model: 'totalMax', style: 'ivu-col-span-12', isShow: false },
        { type: 'textarea', label: '差额说明', placeholder: '请输入差额说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-24', isShow: true },
        { type: 'button', style: 'ivu-col-span-24', isShow: true }
      ],
      rules: {
        handleType: [
          { required: true, message: '请选择开票方式', trigger: 'select' }
        ],
        total: [
          // { required: true, message: '请输入处理差额(不能为0)', trigger: 'blur', pattern: /^-?[1-9]\d*$/ }
          { required: true, message: '请输入处理差额(不能为0)', trigger: 'blur', validator: validateTotal }
        ],
        totalMin: [
          // { required: true, message: '请输入处理差额（只能填写负数）', trigger: 'blur', pattern: /^\-[1-9][0-9]*$/ }
          { required: true, trigger: 'blur', validator: validateTotalMin }
        ],
        totalMax: [
          // { required: true, message: '请输入处理差额（只能填写正数）', trigger: 'blur', pattern: /^\+?[1-9][0-9]*$/ }
          { required: true, trigger: 'blur', validator: validateTotalMax }
        ],
        remark: [
          { required: true, message: '请输入差额说明', trigger: 'select' }
        ]
      },
      arrListDown: {
        balancehandle: []
      },
      rowYear: '',
      rowMonth: '',
      balanceRemarks: [],
      currentRow: {}
    }
  },

  watch: {
  },

  mounted () {
    this.getEnum()
  },

  methods: {
    // 数据字典
    getEnum () {
      let groupName = 'balance.balancehandle'
      Common.getEnum(groupName, this.arrListDown)
      // console.log('数据字典：', this.arrListDown)
    },

    cancel () {
      this.isShowBalanceProcessModal = false
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
      this.tableData = []
    },

    // 确定差额处理
    async handleSubmit () {
      var data = {
        Year: this.currentRow.periodYear,
        Month: this.currentRow.periodMonth,
        EmpID: this.currentRow.empID,
        EmpName: this.currentRow.employeeName,
        IDCardNo: this.currentRow.idCardNo,
        CompanyID: this.currentRow.companyID,
        CompanyName: this.currentRow.companyName,
        InsureNo: this.currentRow.insureNo,
        IsPersonalBurden: this.currentRow.isPerson,
        InsuranceName: this.currentRow.insuranceName,
        InsuranceCode: this.currentRow.insuranceCode,
        Balance: this.currentRow.balanceTotal,
        BalanceRemarks: this.tableData
      }
      console.log('🐟', data)
      let res = await BalanceApi.postPayableBalanceHandleLog(data)
      console.log('确定差额处理res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.isShowBalanceProcessModal = false
        this.$emit('query')
        setTimeout(() => {
          localStorage.removeItem('tempAddBalanceArr')
        }, 500)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 添加差额
    handleAddBalance () {
      var arr = []
      var that = this
      var tempAddBalanceArr = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
      if (tempAddBalanceArr) {
        arr = tempAddBalanceArr
      }
      var that = this
      this.$refs.formData.validate((valid) => {
        if (valid) {
          arr.unshift(this.formData)
          localStorage.setItem('tempAddBalanceArr', JSON.stringify(arr))
          setTimeout(() => {
            that.tableData = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
            Object.keys(that.formData).forEach(key => {
              that.formData[key] = ''
            })
          }, 100)
        }
      })
    },

    // 删除差额
    handleDel (index) {
      this.tableData.splice(index, 1)
      var tempAddBalanceArr = JSON.parse(localStorage.getItem('tempAddBalanceArr'))
      if (tempAddBalanceArr) {
        tempAddBalanceArr.splice(index, 1)
      }
      localStorage.setItem('tempAddBalanceArr', JSON.stringify(tempAddBalanceArr))
    },

    // 处理方式下拉改变
    handleTypeChange (valueObj) {
      console.log('valueObj: ', valueObj)
      if (valueObj) {
        this.formData.handleType = valueObj.value
        this.formData.handleTypeName = valueObj.label
        this.formData.total = ''
        this.formItem.map(item => {
          if ([1, 3].indexOf(+valueObj.value) !== -1) {
            this.formItem[1].isShow = false
            this.formItem[2].isShow = false
            this.formItem[3].isShow = true
          } else if ([2].indexOf(+valueObj.value) !== -1) {
            this.formItem[1].isShow = false
            this.formItem[2].isShow = true
            this.formItem[3].isShow = false
          } else {
            this.formItem[1].isShow = true
            this.formItem[2].isShow = false
            this.formItem[3].isShow = false
          }
        })
      }
    }
  }
}
</script>

<style lang="less" scope>
</style>
